import { Texture } from "pixi.js";

export class TexturePool{
    /**
     * @type {Texture[]}
     */
    static pool=[];

    static newTexture(source){
        let texture=null;
        source=source??Texture.EMPTY._source;
        if(this.pool.length>0){
            texture=this.pool.pop();
            texture.source=source;
        }else{
            texture=new Texture({source});
        }
        if(source.label!='EMPTY'){
            texture.noFrame=true;
            texture.update();
            texture.noFrame=false;
        }
        source.off('resize',texture.update,texture);
        return texture;
    }

    static releaseTexture(texture){
        if(texture.label=='EMPTY')return;
        texture.dynamic=false;
        texture.source=Texture.EMPTY._source;
        Texture.EMPTY._source.off('resize',texture.update,texture);
        texture.frame.x=0;
        texture.frame.y=0;
        texture.noFrame=true;
        texture.update();
        this.pool.push(texture);
    }

    static close(){
        for(let texture of this.pool){
            texture._source=null;
            texture.destroy();
        }
        this.pool.length=0;
    }
}